﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Inspiration.Web.Controllers
{
    public class NewsLetterController : Controller
    {
        //
        // GET: /NewsLetter/
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        
        [HttpPost]
        public ActionResult Index(string SubscribeNewsletter, FormCollection formValues)
        {

            bool wantToSubscribe = bool.Parse(SubscribeNewsletter);
            System.Web.Security.MembershipUser currentUser = System.Web.Security.Membership.GetUser();
            Guid userId = (Guid)currentUser.ProviderUserKey;

            Inspiration.Web.Models.InspirationEntities entitiesRepository = new Models.InspirationEntities();
            Models.NewsLetterSubscriber foundSubscriber = entitiesRepository.NewsLetterSubscribers.Single(users => users.OwnerId == userId);
            bool userIsSubscribed = foundSubscriber != null;

            if (userIsSubscribed)
            {
                if (!wantToSubscribe)
                {
                    entitiesRepository.NewsLetterSubscribers.DeleteObject(foundSubscriber);
                    entitiesRepository.SaveChanges();

                    // Point to consider (Transactions): 
                    // What if we want to do a batch delete...
                    // Do we get a bunch of objects like the following:
                    //IQueryable<Models.NewsLetterSubscriber> subscribers = entitiesRepository.NewsLetterSubscribers.Single(users => users.OwnerId == userId);
                    // Then do something like the following:
                    //foreach (Inspiration.Web.Models.NewsLetterSubscriber subscriber in subscribers)
                    //{
                    //    entitiesRepository.NewsLetterSubscribers.DeleteObject(subscriber);
                    //}
                    //entitiesRepository.SaveChanges();
                }
            }
            else // user is not subscribed
            {
                if (wantToSubscribe)
                {
                    Inspiration.Web.Models.NewsLetterSubscriber subscriber = new Models.NewsLetterSubscriber();
                    subscriber.OwnerName = currentUser.UserName;
                    subscriber.OwnerId = userId;
                    entitiesRepository.NewsLetterSubscribers.AddObject(subscriber);
                    entitiesRepository.SaveChanges();
                }
            }

            if (wantToSubscribe)
                return View("Subscribed");
            else
                return View("Unsubscribed");
        }
    }
}
